package com.iedu.demo.lgq.controller;

import com.iedu.demo.lgq.entity.TbCart;
import com.iedu.demo.lgq.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("cart")
@CrossOrigin
public class CartController {

    @Autowired
    private CartService cartService;

    // 添加商品到购物车
    @PostMapping("/add")
    public String addToCart(TbCart cart) {
        boolean isAdded = cartService.addToCart(cart);
        if (isAdded) {
            return "商品已添加到购物车";
        } else {
            return "购物车中已有该商品，数量已增加";
        }
    }


    // 获取用户购物车所有商品
    @GetMapping("/list/{userName}")
    public List<TbCart> getCartItems(@PathVariable String userName) {
        return cartService.getCartItems(userName);
    }

    // 修改购物车商品数量
    @PutMapping("/update")
    public String updateCartItemQuantity(@RequestParam Long id, @RequestParam int quantity) {
        boolean success = cartService.updateCartItemQuantity(id, quantity);
        return success ? "商品数量更新成功" : "商品数量更新失败";
    }

    // 删除单个购物车商品
    @DeleteMapping("/delete/{id}")
    public String deleteCartItem(@PathVariable Long id) {
        boolean success = cartService.deleteCartItem(id);
        return success ? "商品删除成功" : "商品删除失败";
    }

    // 批量删除购物车商品
    @DeleteMapping("/batchDelete")
    public String batchDeleteCartItems(@RequestBody List<Long> ids) {
        boolean success = cartService.batchDeleteCartItems(ids);
        return success ? "批量删除成功" : "批量删除失败";
    }

    // 购买单个商品
    @PostMapping("/purchase/{id}")
    public String purchaseCartItem(@PathVariable Long id) {
        boolean success = cartService.purchaseCartItem(id);
        return success ? "商品购买成功" : "商品购买失败";
    }

    // 批量购买商品
    @PostMapping("/batchPurchase")
    public String batchPurchaseCartItems(@RequestBody List<Long> ids) {
        boolean success = cartService.batchPurchaseCartItems(ids);
        return success ? "批量购买成功" : "批量购买失败";
    }
}
